<template>
  <div class="cate-edit">
    <div v-if="!isCate">
      <Button type="primary" class="cate-btn" label="提交审核" @click="onSubmitClick" />
      <Button class="cate-btn" label="取消" @click="onCancelClick" />
    </div>

    <el-form class="cateForm" :model="cateData.form" ref="formRef" status-icon :show-message="false" :label-width="110"
             label-position="left">
      <!--      <div v-if="!isCate" class="goodsType">-->
      <!--        <span class="title">选择店铺经营类目</span>-->
      <!--        <el-radio-group v-model="cateData.form.goodsType">-->
      <!--          <el-radio label="HCONSUMABLES">高值耗材</el-radio>-->
      <!--          <el-radio label="LCONSUMABLES">低值耗材</el-radio>-->
      <!--          <el-radio label="INSTRUMENT">器械</el-radio>-->
      <!--          <el-radio label="REAGENT">试剂</el-radio>-->
      <!--          <el-radio label="CONVENTION">常规</el-radio>-->
      <!--        </el-radio-group>-->
      <!--      </div>-->
      <!--      <div v-else class="goodsType"><span class="title">店铺经营类目：</span>{{ consts.GoodsType[cateData.goodsType] }}</div>-->

      <p class="title" v-if="!isCate">选择经营器械类别</p>
      <ApplyCate :isCate="isCate" :cates="cateData.selectedCate" @complete="onCompleteCate" />

      <div class="license" v-if="!isCate">
        <p class="title">上传证件</p>
        <div class="type">
          <div class="type-box" v-for="(cert, index) in cateData.form.certs" :key="index">
            <div class="checkBox-small">
              <el-checkbox v-model="cert.checked" :label="cert.title" size="large" />
            </div>

            <div v-if="cert.checked">
              <div class="checkBox-large">
                <div class="qulification">
                  <el-form-item label="上传证件照片" :prop="`certs[${index}].qualificationImg`" required class="item">
                    <div class="upload-img">
                      <el-upload class="avatar-uploader" accept=".png,.jpg,.jpeg" :action="actionUrl" :headers="headers"
                                 :show-file-list="false" :on-success="(res) => onUploadSuccess(cert, res)"
                                 :before-upload="beforeUpload">
                        <img v-if="cert.qualificationImg" :src="cert.qualificationImg" class="avatar" />
                        <div v-else class="noImg">
                          <el-icon class="avatar-uploader-icon">
                            <Plus />
                          </el-icon>
                          <div class="tip" scope.slot="tip">点击上传</div>
                        </div>
                      </el-upload>
                      <div class="tips">
                        <Link label="查看" class="btn" @click="onShowImgClick(cert.qualificationImg)" />
                        <p class="img-tip">只能上传jpg/png/jpeg文件，且不超过10MB</p>
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item v-if="cert.qualificationType !== 'MEDICAL_DEVICE_BUSINESS_RECORD_CERTIFICATE'"
                                class="time" label="证件生效期" :prop="`certs[${index}].effectiveDate`" required>
                    <el-date-picker v-model="cert.effectiveDate" type="date" placeholder="请选择开始时间"
                                    format="YYYY/MM/DD" value-format="YYYY/MM/DD" clearable />
                    <el-icon class="time-icon">
                      <Minus />
                    </el-icon>
                    <el-date-picker v-model="cert.expiredDate" class="time" type="date" placeholder="请选择到期时间"
                                    format="YYYY/MM/DD" value-format="YYYY/MM/DD" clearable />
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>

    <Record v-if="isCate" :isCate="isCate" :list="cateData.operateList" />
  </div>

  <el-image-viewer ref="previewViewer" v-if="showImageViewer" @close="closeImgView" :url-list="srcList" />
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import { apiBasePath } from '@/api/config'
import api from '@/api'
import consts from '@/consts'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'
import Record from './record.vue'
import ApplyCate from '@/components/cate/apply_cate.vue'

const props = defineProps(['isCate'])
const emit = defineEmits(['complete', 'change'])

const router = useRouter()

const cateData = reactive({
  operateList: [],
  catIdList: [],
  selectedCate: [],
  goodsType: '',
  form: {
    goodsType: '',
    selected: [],
    certs: consts.qualificationType.map((e) => {
      return {
        ...e,
        checked: false,
        qualificationImg: '',
        effectiveDate: '',
        expiredDate: '',
        customerQualificationId: ''
      }
    })
  }
})

let internetLicense = []

const formRef = ref(null)
const showImageViewer = ref(false)
const srcList = ref([])

const actionUrl = apiBasePath + '/medinstrument/third/uploadSingleFile'

const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('_third_token')
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  const isLt1M = file.size / 1024 / 1024 < 10

  if (!isJPG) {
    ElMessage.error('只能上传jpg/png/jpeg文件!')
  }
  if (!isLt1M) {
    ElMessage.error('上传图片大小不能超过 10MB!')
  }
  return isJPG && isLt1M
}

const onUploadSuccess = (cert, res) => {
  cert.qualificationImg = res.data
}

const audit = async () => {
  let qualificationList = cateData.form.certs
    .filter((e) => e.checked === true)
    .map((e) => {
      return {
        qualificationImg: e.qualificationImg,
        expiredDate: e.expiredDate,
        effectiveDate: e.effectiveDate,
        qualificationType: e.qualificationType,
        supplierQualificationId: e.supplierQualificationId
      }
    })

  let supplierQualificationEditFormList = [...qualificationList, ...internetLicense]

  const params = { catIdList: cateData.catIdList, supplierQualificationEditFormList }
  let { err } = await api.post('/medinstrument/third/supplier/updateSupplierCat', params)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('供应商变更类目申请成功')
    emit('complete')
    infoData()
  }
}

const infoData = async () => {
  let { data, err } = await api.get('/medinstrument/third/supplier/information')
  if (err) {
    ElMessage.error(err)
  } else {
    cateData.selectedCate = data.apparatusCategoryIds.map((e) => e)
    const supplierQualificationList = data.supplierQualificationList || []
    const internetCertificate = supplierQualificationList.find((e) => e.qualificationType === 'INTERNET_CERTIFICATE')

    let license = []
    license.push({ ...internetCertificate })

    internetLicense = license.map((e) => {
      return {
        qualificationImg: e.qualificationImg,
        expiredDate: null,
        effectiveDate: null,
        qualificationType: e.qualificationType,
        supplierQualificationId: e.supplierQualificationId
      }
    })

    if (supplierQualificationList.length > 0) {
      cateData.form.certs.forEach((cert) => {
        const qualification = supplierQualificationList.find((e) => cert.qualificationType === e.qualificationType)

        if (qualification) {
          Object.assign(cert, { checked: true }, qualification)
        }
      })
    }
    cateData.goodsType = data.goodsType
    cateData.operateList = data.operateList
    cateData.catIdList = data.apparatusCategoryIds
    cateData.form.goodsType = data.goodsType
  }
}

const onSubmitClick = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      audit()
    }
  })
}

const onCancelClick = () => {
  emit('change')
}

const onCompleteCate = (val) => {
  cateData.catIdList = val
}

const onShowImgClick = (url) => {
  srcList.value = [url]
  showImageViewer.value = true
}

const closeImgView = () => {
  showImageViewer.value = false
}

onMounted(() => {
  infoData()
})
</script>

<style scoped lang="scss">
.cate-edit {
  .cateForm {
    .title {
      height: 20px;
      font-weight: 600;
    }

    .goodsType,
    .license {
      .title {
        display: inline-block;
        margin: 20px 30px 20px 0;
      }
    }

    .license {
      .type {
        .type-box {
          border: 1px solid #dcdfe6;
          margin-bottom: 20px;
          border-radius: 4px;
        }

        .checkBox-small {
          display: flex;
          align-items: center;
          background-color: #fafafa;
          height: 48px;
          line-height: 16px;
          padding-left: 20px;
          border-radius: 4px;
        }

        .checkBox-large {
          .qulification {
            color: #606266;
            padding-left: 10px;

            .el-form-item {
              margin: 0;
            }

            .item {
              margin: 20px 0;

              .upload-img {
                display: flex;
                align-items: flex-end;

                .tips {
                  display: flex;
                  align-items: center;

                  .btn {
                    margin-left: 10px;
                  }

                  .img-tip {
                    font-size: 12px;
                    color: var(--span-color-text);
                    height: 16px;
                    line-height: 16px;
                    margin-left: 12px;
                  }
                }

                .noImg {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  width: 80px;
                  height: 80px;

                  .el-icon svg {
                    width: 25px;
                    height: 25px;
                    margin-bottom: 10px;
                  }

                  .tip {
                    font-size: 12px;
                    line-height: 12px;
                    padding: 0 5px;
                    text-align: center;
                  }
                }
              }
            }

            .time {
              margin-bottom: 30px;

              .time-icon {
                font-size: 8px;
                margin: 0 11px;
                color: var(--span-color-text);
              }
            }
          }
        }
      }
    }
  }
}
</style>
